<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单编号" prop="stoProId">
        <el-input
          v-model="queryParams.stoProId"
          placeholder="请输入订单编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商号" prop="stoSupId">
        <el-input
          v-model="queryParams.stoSupId"
          placeholder="请输入供应商编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:config:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="batch_handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Refresh"
          @click="handleRefreshCache"
          >刷新缓存</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="configList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="stoProId" />
      <el-table-column
        label="供应商"
        align="center"
        prop="supName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="支付类型"
        align="center"
        prop="stoPay"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="进货时间" align="center" prop="stoDate" />
      <el-table-column label="操作者" align="center" prop="roleNameActor1" />
      <el-table-column label="备注" align="center" prop="stoNote" />
      <el-table-column label="审批人" align="center" prop="roleNameActor2" />
      <el-table-column label="审批时间" align="center" prop="appPassdate" />
      <el-table-column
        label="订单状态"
        align="center"
        prop="stoState"
        :formatter="orderStatusFormatter"
      />
      <el-table-column
        label="操作"
        align="center"
        width="268"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="查看物品详细" placement="top">
            <el-button
              type="text"
              icon="Search"
              @click="handleCheckGoods(scope.row)"
              >查看</el-button
            >
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
              >修改</el-button
            >
          </el-tooltip>
          <el-tooltip content="申请入库" placement="top">
            <el-button
              type="text"
              icon="MessageBox"
              @click="apply_storage(scope.row)"
              >入库</el-button
            >
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页插件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.count"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      v-if="open"
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form ref="configRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应商号" prop="stoSupId">
          <el-input v-model="form.stoSupId" placeholder="请输入供应商号" />
        </el-form-item>
        <el-form-item label="支付类型" prop="stoPay">
          <el-select
            v-model="form.stoPay"
            placeholder="请选择支付类型"
            style="width: 500px"
          >
            <el-option
              v-for="item in stoPay_options"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进货时间" prop="stoDate">
          <el-date-picker
            v-model="form.stoDate"
            type="datetime"
            placeholder="请选择进货时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item label="操作者号" prop="stoActor">
          <el-input v-model="form.stoActor" placeholder="请输入操作者号" />
        </el-form-item>
        <el-form-item label="备注" prop="stoNote">
          <el-input v-model="form.stoNote" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="审批人号" prop="appMangerId">
          <el-input v-model="form.appMangerId" placeholder="请输入审批人号" />
        </el-form-item>
        <el-form-item label="审批时间" prop="appPassdate">
          <el-date-picker
            v-model="form.appPassdate"
            type="datetime"
            placeholder="请选择审批时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="stoState">
          <el-select
            v-model="form.stoState"
            placeholder="请选择订单状态"
            style="width: 500px"
          >
            <el-option
              v-for="(item, index) in stoState_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增物品明细的展示框 -->
    <el-dialog
      v-if="second_open"
      :title="second_title"
      v-model="second_open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="configRef"
        :model="newform"
        :rules="rules"
        label-width="80px"
      >
      </el-form>
    </el-dialog>
    <!-- 展示物品明细的弹框 -->
    <el-dialog
      v-if="three_open"
      :title="three_title"
      v-model="three_open"
      width="1000px"
      append-to-body
    >
      <!-- 物品明细搜索表单 -->
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="商品编号" prop="productId">
          <el-input
            v-model="queryParams.productId"
            placeholder="请输入商品编号"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入商品名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="OrderQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 增删按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleOpen('add')"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="batch_handleDelete"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Refresh"
            @click="handleRefreshCache"
            >刷新缓存</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <!-- 物品明细表格 -->
      <el-table
        v-loading="OrderLoading"
        :data="GoodsList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品编号" align="center" prop="productId" />
        <el-table-column
          label="商品名称"
          align="center"
          prop="productName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="商品类型"
          align="center"
          prop="productType"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="商品品牌" align="center" prop="brand" />
        <el-table-column
          label="采购数量"
          align="center"
          prop="purchaseQuantity"
        />
        <el-table-column
          label="采购单价"
          align="center"
          prop="purchaseUnitPrice"
        />
        <el-table-column label="备注" align="center" prop="note" />
        <el-table-column
          label="操作"
          align="center"
          width="150"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                type="text"
                icon="Edit"
                @click="handleOpen('edit', scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="text"
                icon="Delete"
                @click="deleteOrder(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页插件 -->
      <pagination
        v-show="GoodsTotal > 0"
        :total="GoodsTotal"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.count"
        @pagination="handleCheckGoods"
      />
    </el-dialog>

    <!-- 入库申请表格 -->
    <el-dialog
      v-if="four_open"
      :title="four_title"
      v-model="four_open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="configRef"
        :model="condition"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="订单编号" prop="stoId">
          <el-input v-model="condition.search.stoId" readonly />
        </el-form-item>
        <el-form-item label="入库仓库" prop="instoWarehouse">
          <el-select
            v-model="condition.search.instoWarehouse"
            placeholder="请选择入库仓库"
            style="width: 400px"
          >
            <el-option
              v-for="item in warehouse_options"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请人" prop="instoActor">
          <el-input
            v-model="condition.search.instoActor"
            placeholder="请输入申请人"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="newapplyStorage">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增物品详单 -->
    <el-dialog
      v-if="Order_open"
      :title="Order_title"
      v-model="Order_open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="configRef"
        :model="OrderCondition"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="OrderCondition.search.productName" />
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-input v-model="OrderCondition.search.productType" />
        </el-form-item>
        <el-form-item label="商品品牌" prop="brand">
          <el-input v-model="OrderCondition.search.brand" />
        </el-form-item>
        <el-form-item label="采购数量" prop="purchaseQuantity">
          <el-input v-model="OrderCondition.search.purchaseQuantity" />
        </el-form-item>
        <el-form-item label="采购单价" prop="purchaseUnitPrice">
          <el-input v-model="OrderCondition.search.purchaseUnitPrice" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="OrderCondition.search.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="newAddOrderDetail">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Config">
import {
  addConfig,
  applyStorage,
  delConfig,
  delOrderDetail,
  getConfig,
  procConfig,
  queryGoodsList,
  updateConfig,
  updateOrederDetail,
} from "@/api/procurement/proclist";
import { getWareHouse } from "@/api/reserve/check";
import { ref } from "vue";
import { addOrderDetail } from "../../../api/procurement/proclist";

const { proxy } = getCurrentInstance();

const configList = ref([]);
const GoodsList = ref([]);
const open = ref(false);
const second_open = ref(false);
const three_open = ref(false);
const four_open = ref(false);
const Order_open = ref(false);
const loading = ref(true);
const OrderLoading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const GoodsTotal = ref(0);
const title = ref("");
const second_title = ref("");
const three_title = ref("");
const four_title = ref("");
const Order_title = ref("");
const dateRange = ref([]);
const warehouse_options = ref([]);
const stoPay_options = ref([
  { value: "未支付", label: "未支付" },
  { value: "部分支付", label: "部分支付" },
  { value: "已支付", label: "已支付" },
]);
const stoState_options = ref([
  { value: "0", label: "待处理" },
  { value: "1", label: "缺货中" },
  { value: "2", label: "已完成" },
]);

//定义查询对象
const data = reactive({
  form: {},
  newform: {},
  queryParams: {
    page: 1,
    count: 10,
    stoId: undefined,
    stoSupId: undefined,
    productName: undefined,
    productId: undefined,
  },
  rules: {
    configName: [
      { required: true, message: "参数名称不能为空", trigger: "blur" },
    ],
    configKey: [
      { required: true, message: "参数键名不能为空", trigger: "blur" },
    ],
    configValue: [
      { required: true, message: "参数键值不能为空", trigger: "blur" },
    ],
  },
  condition: {
    page: 1,
    count: 10,
    maxPage: 0,
    total: 0,
    index: 0,
    search: {
      stoProId: undefined,
      stoSupId: undefined,
      productName: undefined,
      porductId: undefined,
      stoId: undefined,
      instoDate: undefined,
      instoWarehouse: undefined,
      instoActor: undefined,
    },
  },
  OrderCondition: {
    page: 1,
    count: 10,
    maxPage: 0,
    total: 0,
    index: 0,
    search: {
      productId: undefined,
      stoProId: undefined,
      productName: undefined,
      productType: undefined,
      brand: undefined,
      purchaseQuantity: undefined,
      purchaseUnitPrice: undefined,
      note: undefined,
    },
  },
});

const { queryParams, form, rules, condition, OrderCondition } = toRefs(data);

/** 查询参数列表 */
function getList() {
  loading.value = true;
  condition.value.page = queryParams.value.page;
  condition.value.count = queryParams.value.count;
  procConfig(condition.value).then((response) => {
    configList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  second_open.value = false;
  three_open.value = false;
  four_open.value = false;
  Order_open.value = false;
  reset();
  clearForm();
}

/** 表单重置 */
function reset() {
  form.value = {
    configId: undefined,
    configName: undefined,
    configKey: undefined,
    configValue: undefined,
    configType: "Y",
    remark: undefined,
  };
  condition.value = {
    page: 1,
    count: 10,
    maxPage: 0,
    total: 0,
    index: 0,
    search: {
      stoProId: undefined,
      stoSupId: undefined,
      productName: undefined,
      porductId: undefined,
      stoId: undefined,
      instoDate: undefined,
      instoWarehouse: undefined,
      instoActor: undefined,
    },
  };
  proxy.resetForm("configRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  condition.value.search.stoProId = queryParams.value.stoProId;
  condition.value.search.stoSupId = queryParams.value.stoSupId;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.stoProId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const configId = row.stoProId || ids.value;
  getConfig(configId).then((response) => {
    form.value = response.data;
    open.value = true;
    form.value.configId = configId;
    title.value = "修改采购单";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["configRef"].validate((valid) => {
    if (valid) {
      if (form.value.configId !== undefined) {
        updateConfig(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addConfig(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const configIds = row.stoProId || ids.value;
  proxy.$modal
    .confirm('是否确认删除订单编号为"' + configIds + '"的订单？')
    .then(function () {
      return delConfig(configIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {
      proxy.$modal.msgError("删除失败");
    });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/config/export",
    {
      ...queryParams.value,
    },
    `config_${new Date().getTime()}.xlsx`
  );
}
/** 刷新缓存按钮操作 */
function handleRefreshCache() {
  condition.value = {
    page: 1,
    count: 10,
    maxPage: 0,
    total: 0,
    index: 0,
    search: {
      stoProId: undefined,
      stoSupId: undefined,
    },
  };
  queryParams.value = {
    page: 1,
    count: 10,
    stoProId: undefined,
    stoSupId: undefined,
  };
  getList();
  proxy.$modal.msgSuccess("刷新缓存成功");
}
/**批量删除的方法 */
function batch_handleDelete() {
  proxy.$modal
    .confirm("是否确认删除这些的订单？")
    .then(function () {
      const deletePromises = ids.value.map((id) => delConfig(id));
      return Promise.all(deletePromises);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch((error) => {
      proxy.$modal.msgError(`删除失败: ${error.message}`);
    });
}

/**查看物品明细 */
function handleCheckGoods(row) {
  reset();
  three_open.value = true;
  OrderLoading.value = true;
  three_title.value = "物品详单";
  OrderCondition.value.page = queryParams.value.page;
  OrderCondition.value.count = queryParams.value.count;
  OrderCondition.value.search.stoProId = row.stoProId;
  queryGoodsList(OrderCondition.value).then((response) => {
    GoodsList.value = response.data.list;
    GoodsTotal.value = response.data.total;
    OrderLoading.value = false;
  });
}

// 打开弹窗并设置标题
const handleOpen = (type, row = null) => {
  if (type === "add") {
    Order_title.value = "新增物品信息";
    clearForm();
  } else if (type === "edit" && row) {
    Order_title.value = "修改物品信息";
    fillForm(row);
  }
  Order_open.value = true;
};
// 清空表单
const clearForm = () => {
  OrderCondition.value.search.productId = undefined;
  OrderCondition.value.search.productName = undefined;
  OrderCondition.value.search.productType = undefined;
  OrderCondition.value.search.brand = undefined;
  OrderCondition.value.search.purchaseQuantity = undefined;
  OrderCondition.value.search.purchaseUnitPrice = undefined;
  OrderCondition.value.search.note = undefined;
};

// 填充表单
const fillForm = (row) => {
  OrderCondition.value.search.productId = row.productId;
  OrderCondition.value.search.productName = row.productName;
  OrderCondition.value.search.productType = row.productType;
  OrderCondition.value.search.brand = row.brand;
  OrderCondition.value.search.purchaseQuantity = row.purchaseQuantity;
  OrderCondition.value.search.purchaseUnitPrice = row.purchaseUnitPrice;
  OrderCondition.value.search.note = row.note;
};
/**提交物品明细操作 */
function newAddOrderDetail() {
  if (Order_title.value === "新增物品信息") {
    addOrderDetail(OrderCondition.value.search).then((response) => {
      proxy.$modal.msgSuccess("添加成功");
      clearForm();
      Order_open.value = false;
      queryGoodsList(OrderCondition.value).then((response) => {
        GoodsList.value = response.data.list;
        GoodsTotal.value = response.data.total;
        OrderLoading.value = false;
      });
    });
  } else if (Order_title.value === "修改物品信息") {
    updateOrederDetail(OrderCondition.value.search).then((response) => {
      proxy.$modal.msgSuccess("修改成功");
      clearForm();
      Order_open.value = false;
      queryGoodsList(OrderCondition.value).then((response) => {
        GoodsList.value = response.data.list;
        GoodsTotal.value = response.data.total;
        OrderLoading.value = false;
      });
    });
  }
}
/**删除商品数据的方法 */
function deleteOrder(row) {
  OrderCondition.value.search.productId = row.productId;
  OrderCondition.value.search.stoProId = row.stoProId;
  delOrderDetail(OrderCondition.value.search).then((response) => {
    proxy.$modal.msgSuccess("删除成功");
    clearForm();
    Order_open.value = false;
    queryGoodsList(OrderCondition.value).then((response) => {
      GoodsList.value = response.data.list;
      GoodsTotal.value = response.data.total;
      OrderLoading.value = false;
    });
  });
}
/**搜索物品详情表格信息 */
function OrderQuery() {
  OrderCondition.value.search.productId = queryParams.value.productId;
  OrderCondition.value.search.productName = queryParams.value.productName;
  OrderLoading.value = true;
  queryGoodsList(OrderCondition.value).then((response) => {
    GoodsList.value = response.data.list;
    GoodsTotal.value = response.data.total;
    OrderLoading.value = false;
    clearForm();
  });
}

/**发送入库申请操作 */
function apply_storage(row) {
  reset();
  getWareHouse().then((response) => {
    warehouse_options.value = response.data;
  });
  four_open.value = true;
  four_title.value = "入库申请表";
  condition.value.search.stoId = row.stoProId;
  condition.value.search.instoDate = formatDate(new Date());
}
/**入库申请提交的操作 */
function newapplyStorage() {
  applyStorage(condition.value.search).then((response) => {
    proxy.$modal.msgSuccess("申请已发送等待审批...");
    four_open.value = false;
  });
}

/**将时间格式化的方法 */
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function orderStatusFormatter(row, column, cellValue, index) {
  // 根据订单状态值返回对应的文本
  switch (cellValue) {
    case "0":
      return "待处理";
    case "1":
      return "缺货中";
    case "2":
      return "已完成";
  }
}
setInterval(getList, 15000);
onBeforeUnmount(() => {
  // 清除定时器
  clearInterval(setInterval(getList, 15000));
});
getList();
</script>
